/*
 * Main.fx
 *
 * Created on Mar 31, 2010, 10:44:18 AM
 */

package fxgreader;

import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.control.Label;
import javafx.scene.control.TextBox;
import javafx.scene.effect.BoxBlur;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.geometry.HPos;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import fxgreader.components.CoverFlow;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import fxgreader.Article;
import fxgreader.components.ImageCoverFlowNode;
import fxgreader.components.CoverFlow2;
import fxgreader.components.CoverFlowNode;
import fxgreader.components.TextCoverFlowNode;
import java.lang.System;
import javafx.scene.input.MouseEvent;
import javafx.scene.Cursor;

/**
 * @author perkintang
 */
var scene : Scene = Scene{
                        width: 1280
                        height : 1024
                        fill : Color.BLACK};
var emailL : Label = Label {
                        textFill : Color.WHITE
                        text: "Email:"
                           };
var emailT : TextBox = TextBox {
                            promptText: "yougmail@gmail.com"
                            columns: 20
                            selectOnFocus: true
                                };
var passwdL : Label = Label {
                        textFill : Color.WHITE
                        text: "Password:"
                            };
var passwdT : TextBox = TextBox {
                            promptText: "your password"
                            columns: 20
                            selectOnFocus: true
                            effect: bind if (passwdT.rawText.length() > 0) BoxBlur {} else null
                            onKeyPressed: function (e: KeyEvent): Void {
                                if(e.code == KeyCode.VK_ENTER){
                                     login();
                                }
                            }
                            };
var hb : HBox = HBox{ spacing: 10
                  content:[
                  VBox{ spacing: 17
                        translateY:4
                        nodeHPos: HPos.RIGHT // center nodes vertically within the row
                        content: [emailL,passwdL]
                  }
                  VBox{ spacing: 10
                        nodeHPos: HPos.LEFT // center nodes vertically within the row
                        content: [emailT,passwdT]
                  }
                ]
             }//HBox;
var loginB = Button {
	text: "Sign in"
	action: login
        onKeyPressed: function (e: KeyEvent): Void {
            if(e.code == KeyCode.VK_ENTER){
                 login();
            }
        }
};
def imageview = ImageView {
        image: Image{ url : "{__DIR__}images/Google_Reader.png"};
        cache : true
};
var vb : VBox = VBox{
                  spacing: 20
                  nodeHPos:HPos.CENTER
                  translateX: bind (stage.width - vb.layoutBounds.width)/2 - vb.layoutBounds.minX
                  translateY: bind (stage.height - vb.layoutBounds.height)/2 - vb.layoutBounds.minY
                  content:[imageview,hb,loginB]
};
var loading = Resources.loadingImage;
var loadingview = ImageView {
                        translateY: bind stage.height/2 - 300*1.5/2 - 80 - loading.height;
                        translateX: bind stage.width/2 - loading.width/2;
                        image:  loading
                        cache : true
                    };
var title : Text = Text {
                        id : "title"
                        font: Font { size: 20 }
                        translateY: bind stage.height/2 - 300*1.5/2 - 20;
                        translateX: bind (scene.width - title.boundsInLocal.width)/2
                        textAlignment : TextAlignment.CENTER
                        fill : Color.WHITE
                        };
var unreadTip : TipText = TipText{
                        text : "2000"
                        translateY: bind stage.height - unreadTip.boundsInLocal.height - 20
                        translateX: 0
                        cursor: Cursor.HAND
                        onMouseClicked :function(event:MouseEvent):Void{
                            coverFlow.clear();
                            body.close();
                            title.visible = false;
                            api.onGetReading = afterGetReading;
                            //unset continuationCode
                            api.continuationCode = "";
                            if(api.getReading()){
                                delete loadingview from scene.content;
                                insert loadingview into scene.content;
                            }
                        }
                        };
var tagsTip : TipText = TipText{
                        cursor: Cursor.HAND
                        text : "Tags"
                        translateY: bind stage.height - unreadTip.boundsInLocal.height - 20
                        translateX: bind stage.width/2 - tagsTip.boundsInLocal.width/2
                        onMouseClicked :function(event:MouseEvent):Void{
                                println("api.tags has {sizeof api.tags}");
                                if(sizeof api.tags > 0 and labels.nodeList.size() == 0){
                                    for(tag in api.tags){
                                         println(tag);
                                         var tagnode = TextCoverFlowNode{
                                                            content : tag
                                                            onclick:function (index : Integer):Void{
                                                                     var coverFlowNode = labels.getNode(index) as TextCoverFlowNode;
                                                                     var dist = (stage.width/2 - coverFlowNode.ori_width/2) - coverFlowNode.offsetX;
                                                                     for(node in labels.nodeList){
                                                                          (node as TextCoverFlowNode).offsetx_to = (node as TextCoverFlowNode).offsetX + dist;
                                                                          (node as TextCoverFlowNode).move();
                                                                     }
                                                                     //the first one
                                                                     var firstNode = labels.nodeList.get(0) as CoverFlowNode;
                                                                     if(firstNode.offsetx_to >= 17+10){
                                                                         labels.leftButton.visible = false;
                                                                     }else{
                                                                         labels.leftButton.visible = true;
                                                                     }
                                                                     var lastNode = labels.nodeList.get(labels.nodeList.size() -1) as CoverFlowNode;
                                                                     var max = Main.stage.width;
                                                                     if(lastNode.offsetx_to <= max - 10 - 17 - 200){
                                                                         labels.rightButton.visible = false;
                                                                     }else{
                                                                         labels.rightButton.visible = true;
                                                                     }
                                                                     coverFlow.clear();
                                                                     body.close();
                                                                     title.visible = false;
                                                                     api.onGetReadingByLable = afterGetReadingByLabel;
                                                                     //unset continuationCode
                                                                     api.continuationCode = "";
                                                                     if(api.getReadingByLable((coverFlowNode).content)){
                                                                        delete loadingview from scene.content;
                                                                        insert loadingview into scene.content;
                                                                     }
                                                                }
                                                        };
                                         tagnode.load();
                                         labels.addNode(tagnode);
                                    }
                                }
                                labels.visible = not labels.visible;
                        }
                        };
public var body : TextWindow = TextWindow{
                            translateY: bind stage.height/2 - body.height/2 + 30;
                            translateX: bind stage.width/2 - body.width/2;
                            width: bind stage.width - 100;
                            height: bind stage.height - 400;
                            visible: false
                            onClose : function(){
                                body.visible = false;
                                subImages.visible = false;
                                subImages.clearNode();
                                delete imageViewer from scene.content;
                            }
                        };
var subImages : CoverFlow2 = CoverFlow2{
                                maxWidth : bind stage.width
                                nodeH:200
                                nodeW:200
                                nodes :[]
                                visible:false
                             };
var labels : CoverFlow2 = CoverFlow2{
                            translateY:bind unreadTip.translateY - labels.boundsInLocal.height - 10
                            maxWidth : bind stage.width
                            nodeH:50
                            nodeW:100
                            nodes : []
                            visible: false;
                          };
var imageViewer : ImageWindow = ImageWindow{
                                    translateX: bind stage.width/2 - imageViewer.width/2;
                                    translateY: bind stage.height/2 - imageViewer.height/2
                                    onClose : function(){
                                        delete imageViewer from scene.content;
                                    }
                                }
var n : Number;
var progress = ProgressBar {
	progress: bind ProgressBar.computeProgress( 3, n )
};
var loggingT = Label {
	text: "Signing in ...";
        textFill : Color.WHITE;
}
var coverFlow : CoverFlow;
var stage = Stage {
    title: "FX GReader"
    fullScreen : true
    scene: scene
}
var corverflow ;
public var currentArticle : Article;
public var api : ReaderAPI = ReaderAPI{
        email: bind emailT.rawText
        passwd: bind passwdT.rawText
        onLogin : function(){
               n=1;
               loggingT.text = "feching the reading list ...";
               api.getReading();
               api.getUnreadCount();
        }
        onGetUnreadCount : function(){
               unreadTip.text = "{String.valueOf(api.unreadCount)}+";
        }
        onLoginFailed : function(){
               loggingT.text = "wrong email or password ...";
               loggingT.textFill = Color.RED;
               vb.content = [imageview,loggingT,hb,loginB];
        }
        onGetReading : function(){
               if(api.articles.size() == 0){
                       api.getReading();
                       return;
               }
               loggingT.text = "parseing images ...";
               n=2;
               FX.deferAction(function():Void{
                   scene.content = [coverFlow,title,body,subImages,unreadTip,tagsTip,labels];
                   afterGetReading();
                   });
               
        }
};
function afterGetReading():Void{
       //first click
       delete coverFlow from scene.content;
       setCoverFlowWithNodes();
       insert coverFlow into scene.content;
       delete loadingview from scene.content;
       //after first click
       api.onGetReading = function(){
          var tmp : Article;
          var image : String;
          var width;
          var height;
          var node : CoverFlowNode;
          println("artiles : {api.articles.size()}");
          for(article in api.articles){
              width = 300;
              height = 300;
              tmp = article as Article;
              if(tmp.getImages().size() == 0){
                  var content = tmp.getBody().replaceAll(System.getProperty("line.separator"),"");
                  if(content.length() > 450){
                          content = "{content.substring(0,450)}...";
                  }
                  node= TextCoverFlowNode{
                                objs : [tmp]
                                content : content
                        };
              }else{
                  image = tmp.getImages().get(0) as String;
                  node = ImageCoverFlowNode{
                            objs : [tmp]
                            ori_width: 300
                            ori_height: 300
                            fixed_width : width
                            fixed_height : height
                            imageURL : image as String
              };
              }
              coverFlow.addNode(node);
              }
           coverFlow.newNodesAdded();
           delete loadingview from scene.content;
       };
       coverFlow.lazyLoad = function(){
                if(api.getReading()){
                    delete loadingview from scene.content;
                    insert loadingview into scene.content;
                }
       };
       delete loadingview from scene.content;
}
function afterGetReadingByLabel(label : String):Void{
       //first click
       delete coverFlow from scene.content;
       setCoverFlowWithNodes();
       insert coverFlow into scene.content;
       delete loadingview from scene.content;
       //after first click
       api.onGetReadingByLable = function(label : String){
          var tmp : Article;
          var image : String;
          var width;
          var height;
          var node : CoverFlowNode;
          println("artiles : {api.articles.size()}");
          for(article in api.articles){
              width = 300;
              height = 300;
              tmp = article as Article;
              if(tmp.getImages().size() == 0){
                  var content = tmp.getBody().replaceAll(System.getProperty("line.separator"),"");
                  if(content.length() > 450){
                          content = "{content.substring(0,450)}...";
                  }
                  node= TextCoverFlowNode{
                                objs : [tmp]
                                content : content
                        };
              }else{
                  image = tmp.getImages().get(0) as String;
                  node = ImageCoverFlowNode{
                            objs : [tmp]
                            ori_width: 300
                            ori_height: 300
                            fixed_width : width
                            fixed_height : height
                            imageURL : image as String
              };
              }
              coverFlow.addNode(node);
              }
           coverFlow.newNodesAdded();
           delete loadingview from scene.content;
       };
       coverFlow.lazyLoad = function(){
                if(api.getReadingByLable(label)){
                    delete loadingview from scene.content;
                    insert loadingview into scene.content;
                }
       };
}
function setCoverFlowWithNodes(){
       var nodes : ImageCoverFlowNode[] = [];
       var tmp : Article;
       var image : String;
       var width;
       var height;
       for(article in api.articles){
              width = 300;
              height = 300;
              tmp = article as Article;
              if(tmp.getImages().size() == 0){
                  image = Resources.text;
                  width = 0;
                  height = 0;
              }else{
                  image = tmp.getImages().get(0) as String;
              }
              insert ImageCoverFlowNode{
                        objs : [tmp]
                        ori_width: 300
                        ori_height: 300
                        fixed_width : width
                        fixed_height : height
                        imageURL : image
              } into nodes;
       }
       if(api.articles.size() > 0){
            title.content = (api.articles.get(0) as Article).getTitle();
            title.visible = true;
       }
       n = 3;
       coverFlow = CoverFlow{
            translateY: bind stage.height/2 - 300*1.5/2;
            translateX: bind stage.width/2 - 300*1.5/2;
            nodeH:300
            nodeW:300
            nodes : nodes
            lazyLoad : function(){
                        if(api.getReading()){
                            delete loadingview from scene.content;
                            insert loadingview into scene.content;
                        }
                   }
            onClick : function(node : CoverFlowNode){
                title.visible = true;
                title.content = "";
                title.content = (node.objs[0] as Article).getTitle();
                if(node.indexOfpositionerArray == coverFlow.centerIndex){
                    currentArticle = (node.objs[0] as Article);
                    body.show();
                    if(currentArticle.getImages().size() > 0){
                            var tmpNode : ImageCoverFlowNode;
                            for(image in currentArticle.getImages()){
                                tmpNode = ImageCoverFlowNode{
                                                    ori_width: 200
                                                    ori_height: 200
                                                    fixed_width : 200
                                                    fixed_height : 200
                                                    fraction : 0.0
                                                    backupImage : Resources.exception
                                                    onclick:function (index : Integer):Void{
                                                         var coverFlowNode = subImages.getNode(index) as ImageCoverFlowNode;
                                                         if(coverFlowNode.image != null){
                                                             imageViewer.imageURL = coverFlowNode.imageURL;
                                                             delete imageViewer from scene.content;
                                                             insert imageViewer into scene.content;
                                                         }
                                                         var dist = (stage.width/2 - 200/2) - coverFlowNode.offsetX;
                                                         for(node in subImages.nodeList){
                                                              (node as ImageCoverFlowNode).offsetx_to = (node as ImageCoverFlowNode).offsetX + dist;
                                                              (node as ImageCoverFlowNode).move();
                                                         }
                                                                             //the first one
                                                         var firstNode = subImages.nodeList.get(0) as CoverFlowNode;
                                                         if(firstNode.offsetx_to >= 17+10){
                                                             subImages.leftButton.visible = false;
                                                         }else{
                                                             subImages.leftButton.visible = true;
                                                         }
                                                         var lastNode = subImages.nodeList.get(subImages.nodeList.size() -1) as CoverFlowNode;
                                                         var max = Main.stage.width;
                                                         println(max);
                                                         if(lastNode.offsetx_to <= max - 10 - 17 - 200){
                                                             println("set rightbutton to unvisable");
                                                             subImages.rightButton.visible = false;
                                                         }else{
                                                                 println("set rightbutton to visable");
                                                             subImages.rightButton.visible = true;
                                                         }
                                                    }
                                                    onTooSmall:function(node : ImageCoverFlowNode):Void{
                                                         node.visible = false;
                                                         for(item in subImages.nodeList){
                                                              if((item as ImageCoverFlowNode).visible){
                                                                return;
                                                              }
                                                         }
                                                         subImages.visible = false;
                                                         subImages.clearNode();
                                                    }
                                                    imageURL : image as String};
                                subImages.addNode(tmpNode);
                                tmpNode.load();
                            }
                    subImages.show();
                    }
                }
            }
       };
}
function login():Void{
    loggingT.text = "Signing in ...";
    loggingT.textFill = Color.WHITE;
    api.login();
    vb.content = [imageview,loggingT,progress];
}
function run(__ARGS__ : String[]) {
    scene.content = vb;
    stage
}